<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form isheader" v-if="headerShow">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <a-form-item label="物流类型" v-if="permissionStore.hasPermisson('wllx.cx')">
              <!-- <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" :loading="loading" @search="handleSearch"
              v-model="pageData.dropDownData" :filter-option="false" allow-search allow-clear
              @focus="focusSel">
              <a-option v-for="item in pageData.nameList as any" :value="item.deliveryType">{{
                      item.deliveryType
              }}
              </a-option>
          </a-select> -->
              <a-input allow-clear class="bacClass" placeholder="" v-model="pageData.dropDownData"
                       @press-enter="huiche"/>
            </a-form-item>
          </a-form>
        </div>
        <div>
          <Toolbar :items="pageData.btnList" @add="addHandler" @del="deleteHandler" @select="selectHandler"
                   @export="exports" @import="importHandler" @excel="downloadHandler">
          </Toolbar>
        </div>

      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18"/>
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18"/>
        </a-divider>
      </div>
      <div class="my-tool-bar">
        <!-- '导出', '导入' -->
        <!-- <Toolbar :items="['查询', '新增', '删除']" @add="addHandler" @del="deleteHandler" @select="selectHandler"
            @export="exports" @import="importHandler" @excel="downloadHandler">
        </Toolbar> -->
      </div>
    </template>
    <template #pageTabel>
      <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height:100%;width: 100%;z-index:999 ;">
        <div style="width: 100%; height: 100%">
          <encapsulation-agrid ref="table1Ref" :configaggrid="configTable1"></encapsulation-agrid>
        </div>
      </a-spin>

    </template>
    <a-drawer style="z-index:999" ok-text='保存' cancel-text='关闭' :mask-closable="false"
              :drawer-style="{ 'zIndex': 9999 }" :width="400" :visible="pageData.showAdd" unmountOnClose @ok="sideOk"
              @cancel="pageData.showAdd = false" :ok-loading="pageData.pageLoading">
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <a-form-item label="物流类型" field="deliveryType" :rules="[{ required: true, message: '物流类型必填' }]"
                       label-col-flex="80px" :validate-trigger="['change', 'blur']">
            <a-input class="bacClass" placeholder="" v-model="dataForm.deliveryType"/>
          </a-form-item>
          <a-form-item label="备注" field="remark" label-col-flex="80px">
            <a-textarea class="bacClass" v-model="dataForm.remark" :max-length="400" allow-clear
                        show-word-limit/>
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts">
import {post} from '@/api/http'
import {useTable, useRowKey, useTableColumn, usePagination, useRowSelection} from '@/hooks/table';
import emitter from "@/hooks/useEventBus";
import {ref, reactive, onMounted, toRefs} from 'vue'
import Toolbar from '@/components/Toolbar.vue';
import {Form, Message, Modal} from '@arco-design/web-vue';
import {FormInstance} from '@arco-design/web-vue/es/form';
import {String} from 'lodash';
import {baseURL} from '@/api/axios.config'
import axios from "axios";
import usePermission from '@/store/modules/permission'

import {localeText} from '@/api/aggridZw'
import {pagingList} from '@/api/paging'
import {simplifyMessages} from '@/api/messageSimplification'
import {saveOrUpdateGridState as saveOrUpdateGridState01} from '@/hooks/useGridState'
import buttionRender from '@/components/aggridCellRenDerer/buttionRender.vue'

interface ProcurementType {
  "id": any
  // "serialNumber": any
  "deliveryType": any
  "remark": any
}

export default {
  name: "DeliveryType",
  setup() {
    const pageData = reactive<{
      nameList: [],
      showAdd: boolean,
      sideTitle: string,
      dropDownData: any,
      pageLoading: boolean,
      rHeight: any,
      btnList: any[],
      isEdit: boolean
    }>({
      nameList: [],
      showAdd: false,
      sideTitle: '新增物流类型',
      dropDownData: "",
      pageLoading: false,
      rHeight: "",
      btnList: [],
      isEdit: false
    });
    //设置权限
    // ['查询', '新增', '删除', '导出', '导入']
    const permissionStore = usePermission()

    if (permissionStore.hasPermisson('wllx.cx')) {

      pageData.btnList.push("查询")
    }
    if (permissionStore.hasPermisson('wllx.xz')) {
      pageData.btnList.push("新增")
    }
    if (permissionStore.hasPermisson('wllx.sc')) {
      pageData.btnList.push("删除")
    }
    if (permissionStore.hasPermisson('wllx.xg')) {
      pageData.isEdit = true
    }
    const table1Ref = ref<any>(null)
    const tableColumns = [
      {
        field: '',
        headerCheckboxSelection: true,
        checkboxSelection: true,
        width: 50,
        showDisabledCheckboxes: false,
        pinned: 'left',
      },
      {
        headerName: "序号",
        field: "serialNumber",
        width: 150
      },
      {
        headerName: "物流类型",
        field: "deliveryType",
        width: 150
      },
      {
        headerName: "备注",
        field: "remark",
        width: 150
      },
      {
        headerName: "创建人",
        field: "createName",
        width: 150
      },
      {
        headerName: "创建时间",
        field: "createTime",
        width: 200
      },
      {
        headerName: "最后修改人",
        field: "updateName",
        width: 150
      },
      {
        headerName: "最后修改时间",
        field: "updateTime",
        width: 200
      },
      {
        headerName: '操作',
        field: 'action',
        slotName: 'action',
        width: 150,
        pinned: 'right',
        cellRenderer: buttionRender,
        cellRendererParams: {
          buttonList: [
            {
              type: 'success',
              text: '修改',
              typeName: 'el-button',
              show: pageData.isEdit,
              Callback: (data: any) => {
                editHandler(data)
              },
            },
          ],
          eltagSize: 0,
        },
      }
    ]
    let configTable1 = {
      url: 'purchase/LogisticType/getPage', //接口路径
      queryData: {
        deleteState: 0,
        deliveryType: pageData.dropDownData
      },
      paginationShow: true, //分页是否显示
      invokeiIterface: true, //是否调用接
      rowMultiSelectWithClick: true, //点击行是否多选
      column: tableColumns,
      fileName: 'DeliveryType01'
    }

    const total = ref(0);
    const page = ref(1);
    const size = ref(10);

    function PageSize(val: any) {
      pagination.page = val
      doRefresh();
    }

    function change1(val: any) {
      pagination.pageSize = val
      doRefresh();
    }

    function doRefresh() {
      table1Ref.value.setQuery({
        deleteState: 0,
        deliveryType: pageData.dropDownData
      })
    }

    const {selectedRowKeys, onSelectionChange} = useRowSelection();
    const pagination = usePagination(doRefresh);
    const table = useTable();
    const rowKey = useRowKey("id");
    //下拉框得到焦点
    const focusSel = () => {
      selCxAll({deliveryType: ''})
    }
    //下拉数据
    const options = ref<any>(pageData.nameList);
    const loading = ref(false);
    const handleSearch = (value: any) => {
      if (value) {
        const ob = {deliveryType: value}
        loading.value = true;
        window.setTimeout(() => {
          selCxAll(ob);
          options.value = pageData.nameList;
          loading.value = false;
        }, 200)
      } else {
        options.value = []
      }
    };

    //下拉框查询
    function selCxAll(val: any) {
      post({
        url: "purchase/LogisticType/getFieldValue",
        data: val
      }).then(({data, code}: any) => {
        if (code === 200) {

          // (data as string[]).splice(0, 0, "全部");
          pageData.nameList = data;

        } else {
          Message.error({
            content: "查询失败！",
            duration: 5000,
          });
        }
      });
    }

    onMounted(() => {
      emitter.on("DeliveryType", () => {
        doRefresh();
      });
      pageData.rHeight = document.getElementsByClassName("main-section")[0]?.clientHeight
      //表格的高
      if (pageData.rHeight !== undefined) {
        pageData.rHeight = pageData.rHeight - 200;

        console.log(pageData.rHeight);

      }
      window.addEventListener('resize', () => {
        pageData.rHeight = document.getElementById("BaseInfoSetting")?.clientHeight

        //表格的高
        if (pageData.rHeight !== undefined) {
          pageData.rHeight = pageData.rHeight - 200;
        }

      })
    });
    //查询
    const selectHandler = () => {
      pagination.page = 1
      doRefresh();
    }
    const queryData = reactive({

      clothType: ""
    });
    const addHandler = () => {
      //清空数据
      for (const key in dataForm) {
        if (key == "id") {
          dataForm.id = null;
        } else {
          dataForm[key] = '';
        }
      }
      pageData.showAdd = true
      pageData.sideTitle = '新增物流类型'

    }

    const dataForm = reactive<ProcurementType>({
      "id": null,
      // "serialNumber": '',
      "deliveryType": '',
      "remark": '',
    })

    // 表格准备事件
    const gridOption = ref()
    const colState = ref()
    const gridReady = (params: any) => {
      gridOption.value = params.api
      colState.value = params.columnApi
    }

    const formRef = ref<FormInstance>()
    const sideOk = () => {
      formRef.value?.validate().then((err) => {
        if (!err) {
          if (pageData.sideTitle === "新增物流类型") {
            dataForm.id = null
            pageData.pageLoading = true
            post({
              url: "purchase/LogisticType/insert",
              data: [dataForm],
            }).then((res: any) => {
              if (res.code === 200) {
                formRef.value?.resetFields();
                pageData.showAdd = false;
                doRefresh();
                Message.success({
                  content: "新增成功",
                  duration: 5000,
                });
              } else {
                Message.error({
                  content: res.message,
                  duration: 5000,
                });
              }
            }).finally(() => {
              pageData.pageLoading = false
            })
          } else {
            post({
              url: "purchase/LogisticType/update",
              data: [dataForm],
            }).then((res: any) => {
              if (res.code === 200) {
                formRef.value?.resetFields();
                pageData.showAdd = false;
                doRefresh();
                //清空数据
                for (const key in dataForm) {
                  if (key == "id") {
                    dataForm.id = null;
                  } else {
                    dataForm[key] = '';
                  }
                }
                Message.success({
                  content: "修改成功",
                  duration: 5000,
                });
              } else {
                Message.error({
                  content: simplifyMessages(res.message),
                  duration: 5000,
                });
              }
            });
          }
        }
      });
    }
    const deleteHandler = () => {
      if (table1Ref.value.getSelectedRows().length === 0) {
        Message.error('请先勾选');
        return
      }
      Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        onOk() {
          post({
            url: 'purchase/LogisticType/delete',
            // data: selectedRowKeys.value
            data: table1Ref.value.getSelectedRows().map((o: any) => {
              return o.id
            })
          }).then(({code, data, message}: any) => {
            if (code === 200) {
              Message.success({
                content: '删除成功',
                duration: 5000
              })
              page.value = 1
              doRefresh()
            } else {
              Message.success({
                content: simplifyMessages(message),
                duration: 5000
              })
            }
          })
        }
      })
    }
    const editHandler = (record: ProcurementType) => {
      dataForm.id = Number(record.id);
      // dataForm.serialNumber = record.serialNumber;
      dataForm.deliveryType = record.deliveryType;
      dataForm.remark = record.remark;
      pageData.sideTitle = '修改物流类型'
      pageData.showAdd = true
    };
    //判断是否填写了中文
    const isChiese = (value: string, cb: Function) => {
      return new Promise<void>(resolve => {
        if (window.encodeURI(value).indexOf('%') !== -1) {
          cb('填写的值不能包含中文！')
        }
        resolve()
      })

    }
    //input离开焦点 将小写转大写
    // const inputBlur = () => {
    //     dataForm.serialNumber = dataForm.serialNumber.toUpperCase();
    // }
    //导出
    const exports = () => {
      // if (selectedRowKeys.value.length === 0) {
      //     Message.error('请先勾选')
      //     return
      // }
      if (table1Ref.value.getSelectedRows() === 0) {
        Message.error('请先勾选');
        return
      } else {
        //将表头拼接出来
        let head = "<th>类型编号</th><th>类型名称</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>"
        //拿到当前表格数据与勾选的行做筛选

        let nowRow = table.dataList.filter(function (o) {
          return selectedRowKeys.value.indexOf(o["id"]) !== -1;
        })
        let body = "";
        nowRow.forEach(function (o) {
          body += "<tr><td>" + o["productTypeCode"] + "</td>";
          body += "<td>" + o["productTypeName"] + "</td>";
          body += "<td>" + o["remark"] + "</td>";
          body += "<td>" + o["createName"] + "</td>";
          body += "<td>" + o["createTime"] + "</td>";
          body += "<td>" + o["updateName"] + "</td>";
          body += "<td>" + o["updateTime"] + "</td>";
          body += "</tr>";
        })
        tableToXlsx(head, '产品类型', body)
        console.log(table)
      }
    }

    function tableToXlsx(head: any, filename: any, body: any) {
      const uri = 'data:application/vnd.ms-excel;base64,',
          template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`;

      const a = document.createElement('a');
      a.href = uri + window.btoa(unescape(encodeURIComponent(template)));
      a.download = filename;
      a.click();
      document.removeChild(a);
    }

    //模板下载
    const downloadHandler = () => {
      window.open(baseURL + 'excel')
    }
    //导入
    const importHandler = () => {

      const inputEle: HTMLInputElement = document.createElement('input')
      inputEle.type = 'file'
      inputEle.id = 'fileUploadExcel'
      inputEle.accept = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
      inputEle.addEventListener('change', (e) => {
        const formData = new FormData()
        if (inputEle.files !== null) {
          formData.append('file', inputEle.files[0] || '')
        } else {
          Message.warning('未选择文件！');
          return
        }
        pageData.pageLoading = true
        axios.post(baseURL + '/product/productType/analyseProductTypeModelModel', formData, {
          headers: {
            "Content-Type": 'multipart/form-data',
            "token": sessionStorage.getItem('USER-TOKEN-KEY')
          },
        }).then((result) => {
          if (result.data['code'] === 200) {
            Message.success('导入成功')
          } else {
            Message.error(result.data.message)
          }

        }).finally(() => {
          pageData.pageLoading = false
          doRefresh()
        })
      })
      inputEle.click()
    }
    const headerShow = ref<boolean>(true)
    const handleChange = (_data: any) => {
      table.handleSuccess(_data);
    }
    const defaultColDef = {
      sortable: true,
      resizable: true,
      filter: true,
      // flex: 1
    }
    const huiche = () => {
      selectHandler();
    }
    const localeText1: any = ref(localeText)
    const pagingList1: any = ref(pagingList)
    return {
      colState,
      permissionStore,
      pagingList1,
      huiche,
      localeText1,
      defaultColDef,
      gridOption,
      gridReady,
      total,
      PageSize,
      change1,
      page,
      size,
      deleteHandler,
      sideOk,
      formRef,
      dataForm,
      addHandler,
      selectedRowKeys,
      pagination,
      tableColumns,
      table,
      rowKey,
      pageData,
      queryData,
      editHandler,
      selectHandler,
      // inputBlur,
      isChiese,
      exports,
      options,
      loading,
      handleSearch,
      focusSel,
      downloadHandler,
      importHandler,
      headerShow,
      handleChange,
      table1Ref,
      configTable1
    };
  },
  components: {Toolbar, }
}
</script>
<style scoped lang="less"></style>